package com.hkedou.yuanhuo.shiro.realm;

import com.hkedou.yuanhuo.adminsystem.business.user.mapper.SysUserMapper;
import com.hkedou.yuanhuo.adminsystem.business.user.model.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class ShiroRealm extends AuthorizingRealm {

    Logger logger= LoggerFactory.getLogger("com.hkedou.adminsystem.login");

    @Resource
    SysUserMapper sysUserMapper;

    private static final Logger log = LoggerFactory.getLogger(ShiroRealm.class);

    //角色权限和对应权限添加
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo");
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //添加角色
        simpleAuthorizationInfo.addRole("admin");

        //添加权限
        simpleAuthorizationInfo.addStringPermission("create");

        return simpleAuthorizationInfo;
    }



    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken atoken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) atoken;


        SysUser sysUser=new SysUser();
        sysUser.setLoginid(token.getUsername());
        sysUser.setPassword(new String(token.getPassword()));
        int count = -1;
//        count = sysUserMapper.verification2(sysUser);
        count = sysUserMapper.verification(sysUser.getLoginid(),sysUser.getPassword());
        if(count==1){
        }else{
            throw new IncorrectCredentialsException();
        }

        //这里验证authenticationToken和simpleAuthenticationInfo的信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(sysUser.getLoginid(), sysUser.getPassword(), getName());
        return simpleAuthenticationInfo;

    }
}
